package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * Author: Felix
 * Date: 2022/4/22
 * Desc: 业务数据动态分流
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private OutputTag<JSONObject> dimTag;

    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;

    private Connection conn;

    public TableProcessFunction(OutputTag<JSONObject> dimTag, MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.dimTag = dimTag;
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //注册驱动
        Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        //建立连接
        conn = DriverManager.getConnection(GmallConfig.PHOENIX_URL);
    }

    //处理业务流数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

        //获取当前操作的业务数据库表名
        String table = jsonObj.getString("table");
        //获取操作类型
        String type = jsonObj.getString("type");

        //注意：如果使用maxwell的bootstrap获取历史数据的话，  这个时候类型是bootstrap-insert，我们这里统一设置为insert
        if ("bootstrap-insert".equals(type)) {
            type = "insert";
            jsonObj.put("type", type);
        }

        //拼接从状态中获取配置信息的key
        String key = table + ":" + type;

        //从广播状态中获取当前处理的业务数据 对应的配置信息
        TableProcess tableProcess = broadcastState.get(key);

        if (tableProcess != null) {
            //说明在配置表中，找到了对应的配置信息

            //不管是事实还是维度 ，在向下游传播数据前，都需要加输出目的地一个属性
            String sinkTable = tableProcess.getSinkTable();
            jsonObj.put("sink_table", sinkTable);

            //在向下游传递数据前，将不需要的字段过滤掉
            String sinkColumns = tableProcess.getSinkColumns();
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");
            fiterColumn(dataJsonObj, sinkColumns);

            //根据配置信息进行分流
            String sinkType = tableProcess.getSinkType();
            if (TableProcess.SINK_TYPE_HBASE.equals(sinkType)) {
                //维度 ---- 维度侧输出流中
                ctx.output(dimTag, jsonObj);
            } else if (TableProcess.SINK_TYPE_KAFKA.equals(sinkType)) {
                //事实数据 ---- 主流中
                out.collect(jsonObj);
            }
        } else {
            //说明在配置表中，没有找到对应的配置信息  将数据过滤掉
            System.out.println("No this key In TableProcess:" + key);
        }

    }


    //处理广播流中的配置数据
    //jsonStr  {"database":"gmall1018_realtime","table":"table_process","type":"insert","data":{配置表中一条配置}}
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        //为了处理json方便，将读取到的jsonStr转换为jsonObj
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //从json对象中获取data属性    data属性对应的就是从配置表中读取到的一条配置信息
        JSONObject dataJsonObj = jsonObj.getJSONObject("data");
        //将读到的一条配置信息封装为TableProcess对象
        TableProcess tableProcess = dataJsonObj.toJavaObject(TableProcess.class);

        //获取业务数据库表名
        String sourceTable = tableProcess.getSourceTable();
        //获取操作类型
        String operateType = tableProcess.getOperateType();
        //获取输出类型    hbase--维度       kafka--事实
        String sinkType = tableProcess.getSinkType();
        //获取输出目的地
        String sinkTable = tableProcess.getSinkTable();
        //获取输出字段
        String sinkColumns = tableProcess.getSinkColumns();
        //获取主键
        String sinkPk = tableProcess.getSinkPk();
        //获取建表扩展
        String sinkExtend = tableProcess.getSinkExtend();
        //拼接放到广播状态中的key
        String key = sourceTable + ":" + operateType;

        //如果当前读取到的配置信息是维度配置，并且是insert操作配置
        if (TableProcess.SINK_TYPE_HBASE.equals(sinkType) && "insert".equals(operateType)) {
            //提前将维度表创建出来
            checkTable(sinkTable, sinkColumns, sinkPk, sinkExtend);
        }

        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //将从配置表中读取到的配置信息放到广播状态中
        broadcastState.put(key, tableProcess);

    }

    //创建维度表
    private void checkTable(String tableName, String columnStr, String pk, String ext) {
        if (pk == null) {
            pk = "id";
        }

        if (ext == null) {
            ext = "";
        }
        //拼接建表语句
        StringBuilder createSql = new StringBuilder("create table if not exists " + GmallConfig.PHOENIX_SCHEMA + "." + tableName + "(");

        String[] columnArr = columnStr.split(",");
        for (int i = 0; i < columnArr.length; i++) {
            String column = columnArr[i];
            if (column.equals(pk)) {
                createSql.append(column + " varchar primary key ");
            } else {
                createSql.append(column + " varchar ");
            }
            if (i < columnArr.length - 1) {
                createSql.append(",");
            }
        }

        createSql.append(") " + ext);

        System.out.println("在phoenix中建表的SQL:" + createSql);

        PreparedStatement ps = null;
        try {
            //获取数据库操作对象
            ps = conn.prepareStatement(createSql.toString());
            //执行SQL语句
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("~~~在phoenix中创建维度表失败~~~");
        } finally {
            //释放资源
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //分流前  对data内容进行过滤
    // dataJsonObj:{"tm_name":"xzls","logo_url":"dsfa","id":13}     sinkColumns: id,tm_name
    private void fiterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] fieldArr = sinkColumns.split(",");
        List<String> fieldList = Arrays.asList(fieldArr);

        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!fieldList.contains(entry.getKey()));

    }
}
